package com.wlz.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wlz.config.ProjectConfig;
import com.wlz.model.AccessTokenBean;
import com.wlz.model.SendGZHTemplateBean;
import com.wlz.service.SendService;
import com.wlz.utils.HttpClientUtil;
import com.wlz.utils.WxUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 *  发送推送消息相关服务实现
 *
 * @author wlz
 * @create 2019-11-13 17:30
 **/

@Service("sendService")
public class SendServiceImpl extends BaseImpl implements SendService {

    private Logger logger = LoggerFactory.getLogger(SendServiceImpl.class);

    private final ProjectConfig projectConfig;

    public SendServiceImpl(ProjectConfig projectConfig) {
        this.projectConfig = projectConfig;
    }




    @Override
    public JSONObject sendGZHTemplateMsg(SendGZHTemplateBean sendGZHTemplateBean) {

        JSONObject respData = new JSONObject();

        // 获取access_token
        AccessTokenBean accessTokenBean = null;
        try {
            // 这里获取的是公众号的  access_token
            accessTokenBean = WxUtils.getWxAccessToken("wx83d9fd9392712332","00fb5893688106d73ff9029cea383417");
        } catch (Exception e) {
            respData.put("msg","获取token失败");
            respData.put("code",1);
            logger.error("获取获取access_token 失败",e);
        }
        if (accessTokenBean != null) {
            if (accessTokenBean.getAccess_token() == null && "".equals(accessTokenBean.getAccess_token())) {
                respData.put("msg","获取token失败");
                respData.put("code",1);
                return respData;
            }
        }
        // 访问地址
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessTokenBean.getAccess_token();


//       将参数转换成JSON格式字符串
        String jsonStr = JSON.toJSONString(sendGZHTemplateBean);
        logger.info("jsonStr>>"+jsonStr);

        // 请求发送模板api
        String httpRst = null;
        try {
            httpRst = HttpClientUtil.doPostJson(url,jsonStr);
        } catch (Exception e) {
            logger.error("doPostJson",e);
        }
        if(StringUtils.isNotEmpty(httpRst)){
            JSONObject ret = JSONObject.parseObject(httpRst);
            logger.info("输出httpRst:    " + httpRst);
            if(ret != null && ret.getIntValue("errcode") == 0){
                respData.put("code",0);
                respData.put("msg","发送消息成功");
            }else{
                respData.put("code",1);
                respData.put("msg","发送消息失败");
            }
        }
        return respData;
    }
}
